import os
import requests
import urllib.parse
import json
import time

##cron: 18 8 * * *
##new Env("太平洋汽车自用")

def send_notify(title, content):
    """
    发送通知的函数，支持青龙面板通知和自定义通知
    """
    try:
        # 默认控制台输出
        print(f"【{title}】\n{content}")
        
        # 检查是否在青龙环境中运行
        if "QL_DIR" in os.environ or "QL_URL" in os.environ:
            try:
                from notify import send as ql_send
                ql_send(f"太平洋汽车 - {title}", content)
                return
            except ImportError:
                pass
        
        # Bark通知
        bark_token = os.environ.get('BARK_TOKEN')
        if bark_token:
            bark_url = f"https://api.day.app/{bark_token}/{urllib.parse.quote(title)}/{urllib.parse.quote(content)}"
            requests.get(bark_url, timeout=5)
        
        # ServerChan通知
        serverchan_key = os.environ.get('SERVERCHAN_KEY')
        if serverchan_key:
            serverchan_url = f"https://sctapi.ftqq.com/{serverchan_key}.send"
            requests.post(serverchan_url, data={
                "title": f"太平洋汽车 - {title}",
                "desp": content
            }, timeout=5)
        
    except Exception as e:
        print(f"⚠️ 发送通知失败: {str(e)}")

def process_account(account_data, account_num):
    """处理单个账户的签到流程"""
    result = {
        "success": False,
        "username": "未知用户",
        "login_msg": "未登录",
        "sign_msg": "未签到",
        "point_msg": "未查询"
    }
    
    try:
        # 解析账户数据
        parts = account_data.split('&')
        if len(parts) < 2:
            raise ValueError("账户数据格式错误")
        
        raw_username = urllib.parse.unquote(parts[0])
        raw_password = urllib.parse.unquote(parts[1])
        result["username"] = raw_username
        
        # 登录请求
        login_url = "https://mrobot.pcauto.com.cn/auto_passport3_back_intf/passport3/rest/login_new.jsp?appKey=b5d3828499d0590600000006"
        login_headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Host": "mrobot.pcauto.com.cn"
        }
        
        login_data = {
            "username": raw_username,
            "password": raw_password
        }
        encoded_data = urllib.parse.urlencode(login_data)
        
        login_res = requests.post(login_url, headers=login_headers, data=encoded_data, timeout=10)
        login_result = login_res.json()
        
        if login_result.get("status") == 0:
            result["login_msg"] = f"✅ 登录成功: {login_result.get('message')}"
            cookies = login_res.cookies
            time.sleep(10)
            
            # 签到请求
            sign_url = "https://api.pcauto.com.cn/user-growth/sign/signCenterInfo"
            sign_res = requests.get(sign_url, headers={"Host": "api.pcauto.com.cn"}, cookies=cookies, timeout=10)
            sign_result = sign_res.json()
            
            if sign_result.get("code") == 200:
                result["sign_msg"] = f"🎉 签到成功: {sign_result.get('message')}"
            elif sign_result.get("code") == 500:
                result["sign_msg"] = f"⛔ 签到失败: {sign_result.get('message')}"
            else:
                result["sign_msg"] = f"⚠️ 未知签到状态: {sign_result.get('message')}"
            
            time.sleep(5)
            
            # 积分查询
            point_url = "https://api.pcauto.com.cn/user-growth/user/userInfo"
            point_res = requests.get(point_url, headers={"Host": "api.pcauto.com.cn"}, cookies=cookies, timeout=10)
            point_result = point_res.json()
            
            if point_result.get("code") == 200:
                points = point_result.get("data", {}).get("point", "未知")
                result["point_msg"] = f"📊 当前积分: {points}"
            else:
                result["point_msg"] = "❓ 积分查询失败"
            
            result["success"] = True
            
        else:
            result["login_msg"] = f"❌ 登录失败: {login_result.get('message')}"
        
    except Exception as e:
        result["login_msg"] = f"🔧 执行出错: {str(e)}"
    
    return result

def main():
    account_results = []
    
    try:
        tpyqc_data = os.environ.get('tpyqc_data')
        if not tpyqc_data:
            raise ValueError("❌ 未找到环境变量 tpyqc_data")
        
        accounts = tpyqc_data.split("&&")
        if not accounts:
            raise ValueError("❌ 未找到有效的账户数据")
        
        for i, account_data in enumerate(accounts, 1):
            account_data = account_data.strip()
            if not account_data:
                continue
                
            result = process_account(account_data, i)
            account_results.append(result)
            
            if i < len(accounts):
                time.sleep(5)
        
        # 构建简洁的通知内容
        final_content = []
        success_count = 0
        
        for i, result in enumerate(account_results, 1):
            final_content.append(f"\n账号{i} ({result['username']}):")
            final_content.append(result["login_msg"])
            final_content.append(result["sign_msg"])
            final_content.append(result["point_msg"])
            
            if result["success"]:
                success_count += 1
        
        notify_title = f"太平洋汽车签到: 成功{success_count}/{len(account_results)}"
        send_notify(notify_title, "\n".join(final_content))
        
    except Exception as e:
        send_notify("太平洋汽车签到出错", f"🔧 主程序出错: {str(e)}")

if __name__ == "__main__":
    main()